package com.evzgaga.evzrecon.annotations;

import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.StandardLocation;

@SupportedAnnotationTypes({"com.evzgaga.evzrecon.annotations.CallbackHandler"})
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class AnnotationUsageReportProcessor  extends AbstractProcessor {

    private Writer reportWriter;

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (roundEnv.processingOver()) {
            return false;
        }
        processingEnv.getMessager().printMessage(Kind.NOTE, "Generating report for ServerCallbackHandler usage.");
        try {
            beginReport();

            for (TypeElement annotationType : annotations) {
                processAnnotatedMethods(roundEnv.getElementsAnnotatedWith(annotationType));
            }

            endReport();
        } catch (IOException ex) {
            Logger.getLogger(AnnotationUsageReportProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    private void beginReport() throws IOException {
        FileObject report = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "report.html");
        reportWriter = report.openWriter();
        reportWriter.write("<html><body><h1>Usages of annotation " + CallbackHandler.class.getName() + "</h1>\n");
    }

    public void processAnnotatedMethods(Set<? extends Element> methods) throws IOException {
        for (Element method : methods) {
            CallbackHandler annotation = method.getAnnotation(CallbackHandler.class);
            reportWriter.append("<hr/><b>Method " + method.toString() + "</b><br/>\n");
            reportWriter.append("Callbacks: " + Arrays.toString(annotation.callbacks()) + "\n");
        }
    }

    private void endReport() throws IOException {
        reportWriter.write("</body></html>");
        reportWriter.close();
    }
}
